package wangjg.security.http.tags;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import wangjg.security.core.AuthoritySet;
import wangjg.security.core.validator.AuthorityValidator;

public abstract class AuthorityTag extends BodyTagSupport {
	private static final long serialVersionUID = 1L;

	private static final String USER_SESSION_KEY = "js-user";
	
    private String mode = "display";
    private String authority; //TODO 权限如果是对象类型？
    
    @Override
    public int doStartTag() throws JspException {
    	boolean display="display".equals(mode);
    	boolean granted=checkPopedom();
    	if((!granted && display)||(granted && !display)){
    		return SKIP_BODY;
    	}
        return EVAL_BODY_INCLUDE;  
    }
    
    private boolean checkPopedom(){
    	Object user = this.getUser();
    	Object resource = new AuthoritySet(){
			public Set getAuthorities() {
				HashSet set = new HashSet();
				set.add(getAuthority(authority));
				return set;
			}};
		boolean allow = AuthorityValidator.validate(resource, user);
    	return allow;
    }

	private Object getUser() {
		HttpSession session=this.pageContext.getSession();
		return session.getAttribute(USER_SESSION_KEY);
	}
	
	protected abstract Object getAuthority(String authority);

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}
}
